import * as types from "../types/chooseDeviceModelTypes";
import NetWorkUtil from "../utils/NetWorkUtil";
import ApiConstants from "../common/ApiConstants";
import EnumConstants from "../common/EnumConstants";

const { DeviceListType } = EnumConstants;

export function getDeviceNameList(deviceType, tag, brandId) {
  let ApiCode;
  if (deviceType === DeviceListType.RECYCLE) {
    if (tag === 0) {
      ApiCode = ApiConstants.DEVICEMODEL_RECYCLEPHONE_BRANDLIST;
    } else {
      ApiCode = ApiConstants.DEVICEMODEL_RECYCLEPAD_BRANDLIST;
    }
  } else if (tag === 0) {
    ApiCode = ApiConstants.DEVICEMODEL_SERVICEPHONE_BRANDLIST;
  } else {
    ApiCode = ApiConstants.DEVICEMODEL_SERVICEPAD_BRANDLIST;
  }
  return dispatch => {
    dispatch({ type: types.CHOOSEDEVICE_SUBLIST_INITING });
    NetWorkUtil.getWithoutLogin(ApiCode, { brand_id: brandId })
      .then(res => {
        dispatch({ type: types.CHOOSEDEVICE_SUBLIST_DONE, deviceList: res.list });
      })
      .catch(error => {
        dispatch({ type: types.CHOOSEDEVICE_SUBLIST_ERROR, error });
      });
  };
}

export function getDeviceModelList(deviceType, curTag) {
  return dispatch => {
    dispatch({ type: types.CHOOSEDEVICE_MAINLIST_INITING });
    NetWorkUtil.getWithoutLogin(ApiConstants.DEVICEMODEL_BRANDLIST, {})
      .then(res => {
        let brandId = 1;
        if (res.count > 0) {
          brandId = res.list[0].brand_id;
          dispatch(getDeviceNameList(deviceType, curTag, brandId));
        }
        dispatch({ type: types.CHOOSEDEVICE_MAINLIST_DONE, deviceModels: res.list, brandId });
      })
      .catch(error => {
        dispatch({ type: types.CHOOSEDEVICE_MAINLIST_ERROR, error });
      });
  };
}

export function onTagChange(deviceType, newTag, brandId, refresh) {
  return dispatch => {
    dispatch({ type: types.CHOOSEDEVICE_TAGCHANGE, curTag: newTag });
    refresh && dispatch(getDeviceNameList(deviceType, newTag, brandId));
  };
}

export function onBrandIdChange(deviceType, tag, newBrandId) {
  return dispatch => {
    dispatch({ type: types.CHOOSEDEVICE_BRANDIDCHANGE, brandId: newBrandId });
    dispatch(getDeviceNameList(deviceType, tag, newBrandId));
  };
}
export function unmount() {
  return dispatch => {
    dispatch({ type: types.CHOOSEDEVICE_UNMOUNT });
  };
}
